using System;
using DG.Tweening;
using Rotary;
using Spine;
using Spine.Unity;
using System.Collections;
using System.Collections.Generic;
using KissEcs;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

namespace CanvasUI
{
    /// <summary>
    /// 抽奖轮盘
    /// </summary>
    public class RotaryTable : MonoBehaviour, IUI, IPointerClickHandler
    {
        public RotaryType type;
        public int startIdx = 0;
        public int chosenIdx = 0;
        public Transform front;
        public Transform front2;
        public List<CanvasGroup> haloList;
        public List<CanvasGroup> chosenHaloList;
        public List<Image> skillIconList;
        public Transform halo;
        public Transform chosenHalo;
        public Transform skillIcon;

        public SkeletonGraphic anim;
        public Button drawBtn;
        public Button closeBtn;
        public CanvasGroup skillChoose;
        public Transform bar;
        public GameObject prefab;

        [Header("展示状态时间 --> 控制光环转动初始速度")]
        public float rewardTime;
        public float maxIntervalTime = 0.5f;
        public float timer = 0;
        private bool isDrawing;//正在抽奖
        private bool drawEnd;
        private bool clickdrawBtn;
        public List<int> upgradeSkillList = new();
        public int idxCount;
        [Header("预设")]
        [Tooltip("加速块数量"), Range(2, 9)] public int addSpeedCnt = 4;
        public float perAddSpeed = 0.07f;
        public const float addSpeed = 0.07f;
        public const float decSpeed = 0.04f;
        public float perDeceleration = 0.07f;
        [Tooltip("减速块"), Range(2, 10)] public int decelerationCnt = 5;

        //private bool test = true;
        //private int num = 0;
        private bool isCanIncrease = false;

        // 时间间隔阈值
        public float doubleTapThreshold = 0.35f;

        // 记录上一次触摸结束的时间
        private float lastTapTime = 0;

        private void Awake()
        {
            for (int i = 0; i < halo.childCount; i++)
            {
                haloList.Add(halo.GetChild(i).GetComponent<CanvasGroup>());
            }
            for (int i = 0; i < chosenHalo.childCount; i++)
            {
                chosenHaloList.Add(chosenHalo.GetChild(i).GetComponent<CanvasGroup>());
            }
            for (int i = 0; i < skillIcon.childCount; i++)
            {
                skillIconList.Add(skillIcon.GetChild(i).GetComponent<Image>());
            }
        }

        private void Start()
        {
            InstallEvent();
        }

        private void OnDestroy()
        {
            AssetLoader.Release(this);
            DOTween.KillAll();
        }

        public void OnShow()
        {
            anim.AnimationState.SetAnimation(0, "1", true);
            InitAll();
            //旋转动画
            front.DOLocalRotate(new Vector3(0, 0, 360), 25f, DG.Tweening.RotateMode.FastBeyond360).SetEase(Ease.Linear).SetLoops(-1, LoopType.Restart);
            front2.DOLocalRotate(new Vector3(0, 0, -360), 25f, DG.Tweening.RotateMode.FastBeyond360).SetEase(Ease.Linear).SetLoops(-1, LoopType.Restart);
            EventManager.Fire("PauseGame");
            drawBtn.gameObject.SetActive(true);

            perDeceleration = decSpeed;
            perAddSpeed = addSpeed;
        }

        private void Update()
        {
            if (clickdrawBtn)
            {
                if (!drawEnd)
                {
                    timer += Time.deltaTime;
                    if (timer >= rewardTime)
                    {
                        timer = 0;
                        startIdx++;
                        if (startIdx >= haloList.Count)
                        {
                            startIdx = 0;
                        }
                        SetIdxPos(idxCount, startIdx);
                        AudioMgr.Instance.audioPlayer.PlayOneShot(AudioMgr.Instance.ReturnClip("wheelrotation"));

                    }
                }

            }

            if (isCanIncrease)
            {
                if (Input.touchCount == 1)
                {
                    Touch touch = Input.GetTouch(0);

                    if (touch.phase == TouchPhase.Ended)
                    {
                        // 检查两次触摸结束的时间间隔
                        if (Time.time - lastTapTime < doubleTapThreshold)
                        {
                            // 检测到双击
                            Debug.Log("Double Tap");
                            rewardTime /= 5; // Adjust rewardTime to be 5 times faster
                            perDeceleration /= 5;
                            isCanIncrease = false;
                        }

                        // 更新上一次触摸结束的时间
                        lastTapTime = Time.time;
                    }
                }
            }
        }


        public void OnHide()
        {
            HideSkillBar();
            DOTween.Kill(front, true);
            DOTween.Kill(front2, true);
            EventManager.Fire("ResumeGame");
        }

        private void InstallEvent()
        {
            drawBtn.onClick.AddListener(OnClickDrawBtn);
            closeBtn.onClick.AddListener(() =>
            {
                AudioMgr.Instance.PlayAudio_Click();
                UIGenericMethods.ChangeUIState(skillChoose, false);
                UIManager.Instance.Hide(UI.RotaryTable).Run(() =>
                {
                    UIManager.Instance.GetUI<BattleUI>(UI.Battle).isWaiting = false;
                }).Done();
            });
        }

        /// <summary>
        /// 点击抽奖按钮
        /// </summary>
        private void OnClickDrawBtn()
        {
            AudioMgr.Instance.PlayAudio_Click();
            drawBtn.interactable = false;
            clickdrawBtn = true;
            isDrawing = true;
            isCanIncrease = true;
            startIdx = -1;

            anim.AnimationState.SetAnimation(0, "2", true);
            anim.AnimationState.Complete += OnAnimComplete;
            UpgradeSkill();
            //旋转动画
            front.DOLocalRotate(new Vector3(0, 0, 360), 15f, DG.Tweening.RotateMode.FastBeyond360).SetEase(Ease.Linear).SetLoops(-1, LoopType.Restart);
            front2.DOLocalRotate(new Vector3(0, 0, -360), 15f, DG.Tweening.RotateMode.FastBeyond360).SetEase(Ease.Linear).SetLoops(-1, LoopType.Restart);

            StartCoroutine(StartDrawAni());
            drawBtn.gameObject.SetActive(false);
        }

        public void FillIcon(List<RotaryCell> lists)
        {
            var skillList = World.GetModel<GamingData>().skillList;
            Dictionary<int, SkillInfo> dict = new();
            foreach (SkillInfo info in skillList)
            {
                dict[info.skillID] = info;
            }
            foreach (RotaryCell cell in lists)
            {
                string str = dict[cell.skillId].skillLevel == 5 ? cell.skillId + "_2" : cell.skillId.ToString();
                //Debug.Log($"cellIdx:{cell.idx},cellSkillid:{cell.skillId}");
                IconMaterial.LoadSkillPic(this, skillIconList[cell.idx], str);
            }
        }

        private void SetIdxPos(int num, int idx)
        {
            int close = idx - num;
            if (close < 0)
            {
                //close += 12;
                close += haloList.Count;
            }
            haloList[close].alpha = 0;
            haloList[idx].alpha = 1;
            for (int i = 0; i < num; i++)
            {
                //haloList[idx - i >= 0 ? idx - i : idx - i + 12].alpha = 1 - 0.15f * i;
                haloList[idx - i >= 0 ? idx - i : idx - i + haloList.Count].alpha = 1 - 0.15f * i;
            }

            if (!isDrawing && idx == chosenIdx)
            {
                drawEnd = true;
                for (int i = 0; i < num; i++)
                {
                    //chosenHaloList[idx - i >= 0 ? idx - i : idx - i + 12].alpha = 1;
                    chosenHaloList[idx - i >= 0 ? idx - i : idx - i + chosenHaloList.Count].alpha = 1;
                }
                Invoke("OpenSkillChoose", .1f);
                front.DOLocalRotate(new Vector3(0, 0, 360), 25f, DG.Tweening.RotateMode.FastBeyond360).SetEase(Ease.Linear).SetLoops(-1, LoopType.Restart);
                front2.DOLocalRotate(new Vector3(0, 0, -360), 25f, DG.Tweening.RotateMode.FastBeyond360).SetEase(Ease.Linear).SetLoops(-1, LoopType.Restart);
            }
        }

        private void OpenSkillChoose()
        {
            UIGenericMethods.ChangeUIState(skillChoose, true);
            AudioMgr.Instance.PlayAudio_WheelStop();
        }

        public void InitAll()
        {
            foreach (CanvasGroup group in haloList)
            {
                if (group.alpha != 0)
                {
                    group.alpha = 0;
                }
            }

            haloList[0].alpha = 1;
            foreach (CanvasGroup group in chosenHaloList)
            {
                if (group.alpha != 0)
                {
                    group.alpha = 0;
                }
            }

            isDrawing = false;
            clickdrawBtn = false;
            drawEnd = false;
            idxCount = 0;
            drawBtn.interactable = true;

        }

        private void OnAnimComplete(TrackEntry track)
        {
            anim.AnimationState.Complete -= OnAnimComplete;
            Debug.Log("播放回调动画");
            anim.AnimationState.SetAnimation(0, "3", true);
        }

        /// <summary>
        /// 升级技能
        /// </summary>
        private void UpgradeSkill()
        {
            var skillList = World.GetModel<GamingData>().skillList;
            foreach (int n in upgradeSkillList)
            {
                //Debug.Log(n);
                foreach (SkillInfo info in skillList)
                {
                    if (n == info.skillID)
                    {
                        info.skillLevel++;
                        //Debug.Log($"Level:{info.skillLevel}");
                        EventManager.Fire("GetNewSkill", info);
                        CreateSkillBar(n, info.skillLevel);
                    }
                }
            }
        }

        /// <summary>
        /// 开始抽奖动画
        /// 先快后慢 -- 根据需求调整时间
        /// </summary>
        /// <returns></returns>
        IEnumerator StartDrawAni()
        {
            rewardTime = maxIntervalTime;
            int idx = 2 * 12 + chosenIdx;
            Debug.Log($"idx:{idx}");
            // 加速
            for (int i = 0; i < addSpeedCnt + 1; i++)
            {
                yield return new WaitForSeconds(0.1f);
                rewardTime -= perDeceleration;
            }
            int totalSlots = haloList.Count;
            // 计算减速开始的位置，确保在选中 idx 前 5 到 6 格开始减速
            int decelerationStartIdx = (idx - decelerationCnt + totalSlots - 1) % totalSlots;

            Debug.Log("decelerationStartIdx:" + decelerationStartIdx);

            yield return new WaitForSeconds(rewardTime * 12);

            // 继续加速直到减速起点
            while (startIdx != decelerationStartIdx)
            {
                yield return new WaitForSeconds(rewardTime);
            }

            // 减速阶段
            for (int i = 0; i < decelerationCnt; i++)
            {
                yield return new WaitForSeconds(rewardTime);
                rewardTime += perAddSpeed;
            }

            isDrawing = false;
            isCanIncrease = false;

            //// 确保到达选中位置
            //while (startIdx != chosenIdx)
            //{
            //    yield return new WaitForSeconds(rewardTime);
            //}
        }

        GameObject CreateSkillBar(int skillId, int level)
        {
            var table = World.GetModel<cfg.Tables>().TbSkills.Get(skillId);
            var obj = Instantiate(prefab, bar);
            if (table.Type == cfg.skill.type.PASSIVITY)
            {
                IconMaterial.LoadSkillBGPic(this, obj.GetComponent<Image>(), "passive");
            }
            if (level < 6)
            {
                IconMaterial.LoadSkillBGPic(this, obj.transform.Find("NameBar").GetComponent<Image>(), "normal");
                for (int i = 1; i <= 5; i++)
                {
                    obj.transform.Find($"Star{i}").gameObject.SetActive(true);
                }
                for (int i = 1; i <= level; i++)
                {
                    obj.transform.Find($"Star{i}/Star").gameObject.SetActive(true);
                }
            }
            else
            {
                IconMaterial.LoadSkillBGPic(this, obj.transform.Find("NameBar").GetComponent<Image>(), "max");
                for (int i = 1; i <= 5; i++)
                {
                    obj.transform.Find($"Star{i}").gameObject.SetActive(false);
                }
                obj.transform.Find($"Star3").gameObject.SetActive(false);
                //obj.transform.Find($"Star1/Star").gameObject.SetActive(false);
                obj.transform.Find($"Star3/Star6").gameObject.SetActive(true);
            }
            obj.transform.Find("NameBar/Text").GetComponent<TMP_Text>().text = table.Name[level < 6 ? 0 : 1];

            IconMaterial.LoadSkillPic(this, obj.transform.Find("IconBG/Icon").GetComponent<Image>(), level == 6 ? skillId + "_2" : skillId.ToString());

            SkillInfo info = new() { skillID = skillId, skillLevel = level };
            if (table.Type == cfg.skill.type.PASSIVITY)
            {
                //Debug.Log($"被动技能ID为{info.skillID},等级为{info.skillLevel}");
                obj.transform.Find("Describe").GetComponent<TMP_Text>().text = $"{UIGenericMethods.ReturnSkillDesc(info)}<color=green>+{UIGenericMethods.ReturnSkillValue(info)}%";
            }
            else
            {
                obj.transform.Find("Describe").GetComponent<TMP_Text>().text = UIGenericMethods.ReturnSkillDesc(info);
            }

            obj.SetActive(true);
            return obj;
        }

        private void HideSkillBar()
        {
            for (int i = 0; i < bar.childCount; i++)
            {
                bar.GetChild(i).gameObject.SetActive(false);
            }
        }

        public void OnPointerClick(PointerEventData eventData)
        {
            int clickCount = eventData.clickCount;

            if (isCanIncrease)
            {
                if (clickCount == 1)
                {
                    Debug.Log("单击");
                }
                else
                {
                    Debug.Log("双击");
                    rewardTime /= 5; // Adjust rewardTime to be 5 times faster
                    perDeceleration /= 5;
                    isCanIncrease = false;
                }
            }

        }
    }
}

